/*
 * @Author: huangliangmiao 1127255342@qq.com
 * @Date: 2024-01-18 14:07:50
 * @LastEditors: wangshuixin 2412658453@qq.com
 * @LastEditTime: 2024-12-12 10:22:03
 * @FilePath: \dcy-teaching-spaced:\webCode\demoweb\dcy-web\packages\utils\download.ts
 * @Description: 一些文件下载函数
 */
import { saveAs } from 'file-saver'

type FileType = { type: string } | null

/**
 * 通过url下载文件
 * @param {string} url 文件路径
 * @param {string} fileName 文件名
 * @returns {undefined}
 */
export const downloadFormUrl = function (url: string, fileName: string) {
  saveAs(url, fileName)
}

/**
 * 下载阿里oss资源
 * @param {string} url oss路径
 * @param {string} fileName 文件名
 * @returns {undefined}
 */
export function downloadFormCos(url: string, fileName: string) {
  fetch(url)
    .then(response => response.blob())
    .then((blob) => {
      saveAs(blob, fileName)
    })
}

/**
 * 下载二进制文件流
 * @param {string} Blob 二进制文件
 * @param {string} fileName 文件名
 * @returns {undefined}
 */
export function exportBlobFile(blob: Blob, fileName: string, type: FileType = null) {
  let _blob = null
  if (type)
    _blob = new Blob([blob], { ...type })
  else
    _blob = new Blob([blob])

  const url = window.URL.createObjectURL(_blob)
  saveAs(url, fileName)
}

// 导出
export async function downloadFile(res: Promise<any>, fileName: string='导出列表') {
  if (res.data.type !== 'application/json') { // 获取文件流
    ElMessage.success('文件已下载，请到下载中查看。')
    try {
      const dis = res.headers['content-disposition']
      const filenameRegex = /filename=([^;]+)\.[^;.]+/
      const match = filenameRegex.exec(dis)
      if (match && match.length > 1) {
        const filename = decodeURIComponent(match[1])
        exportBlobFile(res.data, `${filename}.xls`, { type: 'application/vnd.ms-excel' })
      }
      else {
        exportBlobFile(res.data, `${fileName}.xls`, { type: 'application/vnd.ms-excel' })
      }
    }
    catch (e) {
      exportBlobFile(res.data, `${fileName}.xls`, { type: 'application/vnd.ms-excel' })
    }
  }
}